﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Vit.Common.Providers;
using Vit.Common.Helpers;

namespace Vit.Web.Providers.DataSource
{
    public class EnumDataSourceProvider : Vit.Web.Providers.IDataSourceProvider
    {
        protected Type enumType;
        protected ICacheProvider cache;

        public EnumDataSourceProvider(Type enumType, ICacheProvider cache)
        {
            this.enumType = enumType;
            this.cache = cache;
        }

        #region IDataSourceService Members

        public IEnumerable<SelectListItem> GetSourceList(string categoryName)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            var vals = EnumHelper.GetObjectsFromEnum(enumType);
            foreach (var pair in vals)
            {
                items.Add(new SelectListItem()
                {
                    Text = pair.Item1,
                    Value = pair.Item2.ToString()
                });
            }
            return items;
        }

        public string GetTextByValue(string categoryName, object value)
        {
            var items = GetSourceList(categoryName);
            var item = items.FirstOrDefault(o => o.Value == value.ToString());
            return item == null ? string.Empty : item.Text;
        }

        public string GetValueByText(string categoryName, string text, bool insertIfNotExists)
        {
            var items = GetSourceList(categoryName);
            var item = items.FirstOrDefault(o => o.Text == text);
            if (item != null)
                return item.Value;
            return string.Empty;
        }

        #endregion

        #region IProvider Members

        public string Name
        {
            get { return string.Format("DataSource:{0}", enumType.FullName); }
        }

        #endregion
    }
}
